package org.brownflat.lighthouse.monitor;

import org.apache.log4j.Logger;
import org.brownflat.lighthouse.action.Action;
import org.brownflat.lighthouse.ci.Monitorable;
import org.brownflat.lighthouse.device.Device;

public class AnyBrokenBuildTask implements LighthouseTask {
	
	private Monitorable monitorable;
	private Action whenTrue;
	private Action whenFalse;
	private Action whenResetNeeded;
	private boolean broken = false;
	private String name = null;
	private Device device;
	private static final Logger LOG = Logger.getLogger(AnyBrokenBuildTask.class);

	public AnyBrokenBuildTask(String name, Monitorable monitorable, Device device, Action reset, Action positive, Action negative) {
		this.monitorable = monitorable;
		this.device = device;
		this.whenTrue = positive;
		this.whenFalse = negative;
		this.whenResetNeeded = reset;
		this.name = name;
	}

	@Override
	public void run() {
		LOG.debug("Checking for any broken build");
		if(monitorable.hasAnyBrokenBuilds()) {
			if(!broken) {
				device.execute(whenResetNeeded);
			}
			
			broken = true;
			device.execute(whenTrue);
			LOG.error("BROKEN BUILD DETECTED.");
		} else {
			if(broken) {
				LOG.error("BROKEN BUILD FIXED.");
				device.execute(whenResetNeeded);
			}
			LOG.info("BUILDS OK.");
			broken = false;
			device.execute(whenFalse);
		}
	}

	@Override
	public String getName() {
		return name;
	}
}
